<template>
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div slot="header" class="clearfix">
        <span>文件筛选</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="handleSearchList()">
          <i class="el-icon-search"></i>搜索
        </el-button>
      </div>
      <div class="filter-item">
        <el-input
          v-model="listQuery.keyword"
          placeholder="文件名"
          style="width: 200px;"
          prefix-icon="el-icon-search"
          clearable
        />
        <el-select
          v-model="listQuery.fileType"
          placeholder="文件类型"
          clearable
          style="margin-left: 10px; width: 120px;"
        >
          <el-option
            v-for="item in fileTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-button @click="handleSearchList()" style="margin-left: 10px;">搜索</el-button>
        <el-button @click="listQuery = Object.assign({}, defaultListQuery); handleSearchList()">重置</el-button>
      </div>
      <div class="action-buttons">
        <el-button
          type="primary"
          icon="el-icon-upload"
          @click="handleAddFile"
        >
          添加文件
        </el-button>
      </div>
    </el-card>

    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>
    </el-card>

    <div class="table-container">
      <el-table
        ref="fileTable"
        :data="list"
        style="width: 100%;"
        v-loading="listLoading"
        border
      >
        <el-table-column label="编号" width="100" align="center">
          <template slot-scope="scope">{{ scope.row.id }}</template>
        </el-table-column>
        <el-table-column label="文件名" min-width="200">
          <template slot-scope="scope">
            <span>{{ scope.row.fileName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="文件类型" width="120" align="center">
          <template slot-scope="scope">{{ scope.row.fileType }}</template>
        </el-table-column>
        <el-table-column label="文件大小" width="120" align="center">
          <template slot-scope="scope">{{ scope.row.fileSize | formatFileSize }}</template>
        </el-table-column>
        <el-table-column label="上传者" width="120" align="center">
          <template slot-scope="scope">{{ scope.row.uploader }}</template>
        </el-table-column>
        <el-table-column label="上传时间" width="160" align="center">
          <template slot-scope="scope">{{ scope.row.uploadTime }}</template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status | statusFilter">
              {{ scope.row.status | statusTextFilter }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleDownloadFile(scope.$index, scope.row)"
            >
              下载
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="handlePreviewFile(scope.$index, scope.row)"
              v-if="isPreviewable(scope.row.fileType)"
            >
              预览
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleDeleteFile(scope.$index, scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
        :current-page.sync="listQuery.page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="listQuery.size"
        :total="total"
      />
    </div>

    <el-dialog
      title="文件预览"
      :visible.sync="previewDialogVisible"
      width="80%"
    >
      <div v-if="previewFileType === 'image'">
        <img :src="previewFileUrl" style="max-width: 100%;" />
      </div>
      <div v-else-if="previewFileType === 'pdf'">
        <iframe :src="previewFileUrl" style="width: 100%; height: 600px;"></iframe>
      </div>
      <div v-else>
        <p>该文件类型不支持在线预览</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="previewDialogVisible = false">关 闭</el-button>
        <el-button type="primary" @click="handleDownloadFile(null, previewFile)">下 载</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="添加文件"
      :visible.sync="addDialogVisible"
      width="50%"
    >
      <el-form
        ref="addForm"
        :model="addForm"
        :rules="addRules"
        label-width="100px"
      >
        <el-form-item label="文件名称" prop="fileName">
          <el-input v-model="addForm.fileName" placeholder="请输入文件名称" />
        </el-form-item>
        <el-form-item label="文件描述" prop="description">
          <el-input
            v-model="addForm.description"
            type="textarea"
            placeholder="请输入文件描述"
          />
        </el-form-item>
        <el-form-item label="文件" prop="file">
          <el-upload
            class="upload-demo"
            drag
            :auto-upload="false"
            :on-change="handleFileChange"
            :show-file-list="true"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="addForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddForm">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="上传文件"
      :visible.sync="uploadDialogVisible"
      width="50%"
    >
      <el-upload
        class="upload-demo"
        drag
        :action="uploadUrl"
        :headers="uploadHeaders"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :before-upload="beforeUpload"
        multiple
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传jpg/png/pdf/doc/docx/xls/xlsx文件，且不超过10MB</div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="uploadDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listFiles, deleteFile, downloadFile, getFileDetail, initUpload, uploadFile } from '@/api/storage'

const defaultListQuery = {
  page: 1,
  size: 10,
  keyword: null,
  fileType: null
}

const fileTypeOptions = [
  {
    label: '图片',
    value: 'image'
  },
  {
    label: '文档',
    value: 'document'
  },
  {
    label: '视频',
    value: 'video'
  },
  {
    label: '音频',
    value: 'audio'
  }
]

export default {
  name: 'StorageList',
  filters: {
    formatFileSize(size) {
      if (!size) return '0 B'
      const units = ['B', 'KB', 'MB', 'GB']
      let unitIndex = 0
      let fileSize = size
      while (fileSize >= 1024 && unitIndex < units.length - 1) {
        fileSize /= 1024
        unitIndex++
      }
      return fileSize.toFixed(2) + ' ' + units[unitIndex]
    },
    statusFilter(status) {
      const statusMap = {
        0: 'info',
        1: 'success'
      }
      return statusMap[status]
    },
    statusTextFilter(status) {
      const statusTextMap = {
        0: '未启用',
        1: '已启用'
      }
      return statusTextMap[status]
    }
  },
  data() {
    return {
      listQuery: Object.assign({}, defaultListQuery),
      list: null,
      total: 0,
      listLoading: false,
      fileTypeOptions: fileTypeOptions,
      previewDialogVisible: false,
      previewFile: null,
      previewFileType: '',
      previewFileUrl: '',
      uploadDialogVisible: false,
      uploadUrl: import.meta.env.VITE_API_BASE_URL + '/api/storage/file/upload',
      uploadHeaders: {
        'Authorization': 'Bearer ' + localStorage.getItem('token')
      },
      addDialogVisible: false,
      addForm: {
        fileName: '',
        description: '',
        status: 1,
        file: null
      },
      addRules: {
        fileName: [{ required: true, message: '请输入文件名称', trigger: 'blur' }],
        file: [{ required: true, message: '请选择文件', trigger: 'change' }]
      },
      selectedFile: null
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleSearchList() {
      this.listQuery.page = 1
      this.getList()
    },
    handleAddFile() {
      this.addDialogVisible = true
      this.addForm = {
        fileName: '',
        description: '',
        status: 1,
        file: null
      }
      this.selectedFile = null
    },
    handleFileChange(file) {
      this.selectedFile = file.raw
      this.addForm.fileName = file.name
    },
    submitAddForm() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          if (!this.selectedFile) {
            this.$message.error('请选择文件')
            return
          }
          
          // 准备初始化上传的数据
          const uploadInitData = {
            fileName: this.addForm.fileName,
            fileSize: this.selectedFile.size
          }
          
          // 初始化上传
          initUpload(uploadInitData).then(response => {
            const fileId = response.data.fileId
            
            // 创建FormData对象用于上传文件
            const formData = new FormData()
            formData.append('file', this.selectedFile)
            formData.append('fileId', fileId)
            
            // 上传文件
            uploadFile(formData, fileId).then(() => {
              this.$message({
                message: '添加成功',
                type: 'success',
                duration: 1000
              })
              this.addDialogVisible = false
              this.getList()
            }).catch(error => {
              this.$message({
                message: '文件上传失败',
                type: 'error',
                duration: 1000
              })
            })
          }).catch(error => {
            this.$message({
              message: '初始化上传失败',
              type: 'error',
              duration: 1000
            })
          })
        }
      })
    },
    handleDownloadFile(index, row) {
      downloadFile(row.id).then(response => {
        const blob = new Blob([response.data])
        const link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = row.fileName
        link.click()
        URL.revokeObjectURL(link.href)
      })
    },
    handlePreviewFile(index, row) {
      this.previewFile = row
      if (row.fileType.startsWith('image')) {
        this.previewFileType = 'image'
        this.previewFileUrl = import.meta.env.VITE_API_BASE_URL + '/api/storage/file/download/' + row.id
      } else if (row.fileType === 'application/pdf') {
        this.previewFileType = 'pdf'
        this.previewFileUrl = import.meta.env.VITE_API_BASE_URL + '/api/storage/file/download/' + row.id
      } else {
        this.previewFileType = 'other'
        this.previewFileUrl = ''
      }
      this.previewDialogVisible = true
    },
    handleDeleteFile(index, row) {
      this.$confirm('是否要删除该文件?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteFile(row.id).then(response => {
          this.$message({
            message: '删除成功',
            type: 'success',
            duration: 1000
          })
          this.getList()
        })
      })
    },
    handleSizeChange(val) {
      this.listQuery.size = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    handleUploadSuccess(response, file, fileList) {
      this.$message({
        message: '上传成功',
        type: 'success',
        duration: 1000
      })
      this.uploadDialogVisible = false
      this.getList()
    },
    handleUploadError(err, file, fileList) {
      this.$message({
        message: '上传失败',
        type: 'error',
        duration: 1000
      })
    },
    beforeUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        this.$message.error('上传文件大小不能超过 10MB!')
      }
      return isLt10M
    },
    isPreviewable(fileType) {
      return fileType.startsWith('image') || fileType === 'application/pdf'
    },
    getList() {
      this.listLoading = true
      listFiles(this.listQuery).then(response => {
        this.listLoading = false
        this.list = response.data.records
        this.total = response.data.total
      }).catch(() => {
        this.listLoading = false
      })
    }
  }
}
</script>

<style scoped>
.filter-container {
  margin-bottom: 15px;
}

.operate-container {
  margin-bottom: 15px;
}

.table-container {
  margin-bottom: 15px;
}

.pagination-container {
  display: inline-block;
  float: right;
}

.upload-demo {
  text-align: center;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  margin-top: -10px;
  margin-bottom: 10px;
}
</style>